﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace QunProject.Common
{
    /// <summary>
    /// 文件帮助类（包含上传）
    /// </summary>
    public class FileHelper
    {
        /// <summary>
        /// 文件类型
        /// </summary>
        public enum FileTypes
        {
            /// <summary>
            /// 图片
            /// </summary>
            图片 = 0,
            /// <summary>
            /// 视频
            /// </summary>
            视频 = 1,
            /// <summary>
            /// 音频
            /// </summary>
            音频 = 2,
            /// <summary>
            /// 文档 WORD PPT EXCEL
            /// </summary>
            文档_W_E_P = 3,
            /// <summary>
            /// 文档 WORD EXCEL
            /// </summary>
            文档_W_E = 4,
            /// <summary>
            /// 文档 WORD PPT
            /// </summary>
            文档_W_P = 5,
            /// <summary>
            /// 文档 PPT EXCEL
            /// </summary>
            文档_E_P = 6,
            /// <summary>
            /// 文档 WORD
            /// </summary>
            文档_W = 7,
            /// <summary>
            /// 文档 EXCEL
            /// </summary>
            文档_E = 8,
            /// <summary>
            /// 文档 PPT
            /// </summary>
            文档_P = 9,
            /// <summary>
            /// 压缩文件
            /// </summary>
            压缩文件 = 10,
            /// <summary>
            /// 不限制
            /// </summary>
            不限制 = 11
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        public class FileUpload
        {
            /// <summary>
            /// 上传文件后缀例举
            /// </summary>
            private Dictionary<int, string[]> FileExpand
            {
                get
                {
                    var _list = new Dictionary<int, string[]>();
                    _list.Add((int)FileTypes.图片, new string[] { "jpg", "gif", "png", "jpeg", "bmp" });
                    _list.Add((int)FileTypes.视频, new string[] { "mp4", "flv" });
                    _list.Add((int)FileTypes.音频, new string[] { "mp3" });
                    _list.Add((int)FileTypes.文档_E, new string[] { "xls", "xlsx" });
                    _list.Add((int)FileTypes.文档_E_P, new string[] { "xls", "xlsx", "ppt", "pptx" });
                    _list.Add((int)FileTypes.文档_P, new string[] { "ppt", "pptx" });
                    _list.Add((int)FileTypes.文档_W, new string[] { "doc", "docx" });
                    _list.Add((int)FileTypes.文档_W_E, new string[] { "doc", "docx", "xls", "xlsx" });
                    _list.Add((int)FileTypes.文档_W_E_P, new string[] { "doc", "docx", "xls", "xlsx", "ppt", "pptx" });
                    _list.Add((int)FileTypes.文档_W_P, new string[] { "doc", "docx", "ppt", "pptx" });
                    _list.Add((int)FileTypes.压缩文件, new string[] { "zip", "rar", "7z" });
                    _list.Add((int)FileTypes.不限制, new string[] { });
                    return _list;
                }
            }
            /// <summary>
            /// 限制文件类型
            /// </summary>
            public FileTypes FileType { get; set; }
            /// <summary>
            /// 文件大小（单位：KB）
            /// </summary>
            public int FileSize { get; set; }
            /// <summary>
            /// 异常信息
            /// </summary>
            public string ErrorMag = string.Empty;
            /// <summary>
            /// 系统模块名称
            /// </summary>
            public string SystemName = string.Empty;

            private string _DomainUrl;
            /// <summary>
            /// 文件地址
            /// </summary>
            public string DomainUrl
            {
                get
                {
                    if (_DomainUrl.IsNullOrWhiteSpace())
                    {
                        _DomainUrl = System.Configuration.ConfigurationManager.AppSettings["DomainUrl"];
                    }
                    return _DomainUrl;
                }
                set
                {
                    _DomainUrl = value;
                }
            }

            /// <summary>
            /// 实例化一个上传实体
            /// </summary>
            /// <param name="_fileType">限制文件类型</param>
            /// <param name="_fileSize">文件大小（单位：KB）</param>
            /// <param name="_systemName">系统模块名称（/Upload/_systemName）</param>
            public FileUpload(FileTypes _fileType = FileTypes.不限制, int _fileSize = 2048, string _systemName = "")
            {
                FileType = _fileType;
                FileSize = _fileSize;
                SystemName = _systemName;
            }

            /// <summary>
            /// 图片Base64方式上传
            /// </summary>
            /// <param name="_base64">图片Base64字符串</param>
            /// <returns></returns>
            public string Base64(string _base64)
            {
                string fileName = Guid.NewGuid().ToString("N") + ".png";
                string systemPath = HttpContext.Current.Server.MapPath("/");
                string filePath = "Upload/" + (SystemName.IsNullOrWhiteSpace() ? "" : SystemName + "/") + DateTime.Now.ToString("yyyy/MM/dd/");
                if (!Directory.Exists(systemPath + filePath))
                    Directory.CreateDirectory(systemPath + filePath);

                Bitmap bmp = _base64.ToBitmap();
                bmp.Save(systemPath + filePath + fileName);
                return filePath + fileName;
            }

            /// <summary>
            /// 文件HttpPosted方式上传
            /// </summary>
            /// <param name="file">HttpPostedFileBase</param>
            /// <returns></returns>
            public string HttpPosted(HttpPostedFileBase file)
            {
                string fileName = Guid.NewGuid().ToString("N");
                string systemPath = HttpContext.Current.Server.MapPath("/");
                string filePath = "/Upload/" + (SystemName.IsNullOrWhiteSpace() ? "" : SystemName + "/") + DateTime.Now.ToString("yyyy/MM/dd/");
                string savePath = systemPath + filePath;
                if (!Directory.Exists(savePath))
                    Directory.CreateDirectory(savePath);

                if (!ValidateSize(file.ContentLength / 1024))
                    return string.Empty;
                var fileExpand = file.FileName.Substring(file.FileName.LastIndexOf('.'));
                if (!ValidateExpand(fileExpand))
                    return string.Empty;
                fileName += fileExpand;

                file.SaveAs(savePath+ fileName);
                return filePath + fileName;
            }

            /// <summary>
            /// 文件HttpPosted方式上传
            /// </summary>
            /// <param name="file">HttpPostedFile</param>
            /// <returns></returns>
            public string HttpPosted(HttpPostedFile file)
            {
                string fileName = Guid.NewGuid().ToString("N");
                string systemPath = HttpContext.Current.Server.MapPath("/");
                string filePath = "Upload/" + (SystemName.IsNullOrWhiteSpace() ? "" : SystemName + "/") + DateTime.Now.ToString("yyyy/MM/dd/");
                if (!Directory.Exists(systemPath + filePath))
                    Directory.CreateDirectory(systemPath + filePath);

                if (!ValidateSize(file.ContentLength / 1024))
                    return string.Empty;
                var fileExpand = file.FileName.Substring(file.FileName.LastIndexOf('.'));
                if (!ValidateExpand(fileExpand))
                    return string.Empty;
                fileName += fileExpand;

                file.SaveAs(systemPath + filePath + fileName);
                return filePath + fileName;
            }

            /// <summary>
            /// 验证文件大小
            /// </summary>
            /// <param name="_size">文件大小（单位：KB）</param>
            /// <returns></returns>
            public bool ValidateSize(int _size)
            {
                var isOk = false;
                if (FileSize == 0)
                {
                    isOk = true;
                }
                else
                {
                    if (FileSize >= _size)
                    {
                        isOk = true;
                    }
                    else
                    {
                        ErrorMag = $"文件大小限制{FileSize}KB Error:{_size}";
                    }
                }
                return isOk;
            }

            /// <summary>
            /// 验证文件后缀名
            /// </summary>
            /// <param name="_expand">扩展名，格式[x|.x]</param>
            /// <returns></returns>
            public bool ValidateExpand(string _expand)
            {
                var isOk = false;
                if (FileType == FileTypes.不限制)
                {
                    isOk = true;
                }
                else
                {
                    _expand = _expand.Trim(new[] { '.' });
                    var expands = FileExpand[(int)FileType];
                    if (expands.Where(x => x == _expand).Any())
                    {
                        isOk = true;
                    }
                    else
                    {
                        ErrorMag = $"文件格式限制{FileType.ToString()}{expands.ToJson()} Error:{_expand}";
                    }
                }
                return isOk;
            }

        }
    }
}
